import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
// import 'package:vehicle_management/config/HttpUtils.dart';
import 'package:vehicle_management/config/Config.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //焦点
  FocusNode _focusNodeUserName = new FocusNode();
  FocusNode _focusNodePassWord = new FocusNode();

  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userNameController = new TextEditingController();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

//用户名
  var _userName;
  var _password;
  var _isShowPwd = false; //是否显示密码
  var _isShowClear = false;

//是否显示输入框尾部的清除按钮

  @override
  void initState() {
    //设置焦点监听
    _focusNodeUserName.addListener(_focusNodeListener);
    _focusNodePassWord.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userNameController.addListener(() {
      print(_userNameController.text);

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNameController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusNodeUserName.removeListener(_focusNodeListener);
    _focusNodePassWord.removeListener(_focusNodeListener);
    _userNameController.dispose();
    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodeUserName.hasFocus) {
      print("用户名框获取焦点");
      // 取消密码框的焦点状态
      _focusNodePassWord.unfocus();
    }
    if (_focusNodePassWord.hasFocus) {
      print("密码框获取焦点");
      // 取消用户名框焦点状态
      _focusNodeUserName.unfocus();
    }
  }

  /// 验证用户名

  String validateUserName(value) {
   
    if (value.isEmpty) {
      return '用户名不能为空!';
    } 
    return null;
  }

  /// 验证密码

  String validatePassWord(value) {
    if (value.isEmpty) {
      return '密码不能为空';
    } else if (value.trim().length < 6 || value.trim().length > 18) {
      return '密码长度不正确';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // logo 图片区域
    Widget logoImageArea = new Container(
        alignment: Alignment.center,
        // 设置图片为圆形
        child: Text(
          "登录",
          style: TextStyle(
              color: Colors.white,
              fontSize: ScreenUtil().setSp(60),
              fontWeight: FontWeight.bold),
        ));

    //输入文本框区域
    Widget inputTextArea = new Container(
      margin: EdgeInsets.only(left: 55, right: 55),
      child: new Form(
        key: _formKey,
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new TextFormField(
              controller: _userNameController,
              focusNode: _focusNodeUserName,
              //设置键盘类型
              keyboardType: TextInputType.number,
              style: TextStyle(fontSize: 18, color: Colors.white),
              decoration: InputDecoration(
                labelText: "用户名",
                hintText: "请输入用户名",
                labelStyle: TextStyle(
                    fontSize: ScreenUtil().setSp(32),
                    color: Colors.white), //设置文字样式
                hintStyle: TextStyle(
                    fontSize: ScreenUtil().setSp(32),
                    color: Colors.white), //设置聚焦文字样式
                helperStyle: TextStyle(
                    fontSize: ScreenUtil().setSp(28),
                    color: Colors.white), //设置帮助文字样式
                errorStyle:
                    TextStyle(fontSize: ScreenUtil().setSp(26)), //设置错误文字样式
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(45),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(45),
                  borderSide: BorderSide(color: Colors.white),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(45),
                  borderSide: BorderSide(color: Colors.white),
                ),
                prefixIcon: Icon(
                  Icons.person,
                  color: Colors.white,
                ),
                //尾部添加清除按钮
                suffixIcon: (_isShowClear)
                    ? IconButton(
                        icon: Icon(
                          Icons.clear,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          // 清空输入框内容
                          _userNameController.clear();
                        },
                      )
                    : null,
              ),
              //验证用户名
              validator: validateUserName,
              //保存数据
              onSaved: (String value) {
                _userName = value;
              },
            ),
            new SizedBox(
              height: ScreenUtil().setHeight(30),
            ),
            new TextFormField(
              focusNode: _focusNodePassWord,
              style: TextStyle(fontSize: 18, color: Colors.white),
              decoration: InputDecoration(
                  labelText: "密码",
                  hintText: "请输入密码",
                  labelStyle: TextStyle(
                      fontSize: ScreenUtil().setSp(32),
                      color: Colors.white), //设置文字样式
                  hintStyle: TextStyle(
                      fontSize: ScreenUtil().setSp(32),
                      color: Colors.white), //设置聚焦文字样式
                  helperStyle: TextStyle(
                      fontSize: ScreenUtil().setSp(28),
                      color: Colors.white), //设置帮助文字样式
                  errorStyle:
                      TextStyle(fontSize: ScreenUtil().setSp(26)), //设置错误文字样式
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(45),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(45),
                    borderSide: BorderSide(color: Colors.white),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(45),
                    borderSide: BorderSide(color: Colors.white),
                  ),
                  prefixIcon: Icon(
                    Icons.lock,
                    color: Colors.white,
                  ),

                  // 是否显示密码
                  suffixIcon: IconButton(
                    icon: Icon(
                        (_isShowPwd) ? Icons.visibility : Icons.visibility_off,
                        color: Colors.red),
                    // 点击改变显示或隐藏密码
                    onPressed: () {
                      setState(() {
                        _isShowPwd = !_isShowPwd;
                      });
                    },
                  )),
              obscureText: !_isShowPwd,
              //密码验证
              validator: validatePassWord,
              //保存数据
              onSaved: (String value) {
                _password = value;
              },
            )
          ],
        ),
      ),
    );

    // 登录按钮区域
    Widget loginButtonArea = new Container(
      margin: EdgeInsets.only(left: 55, right: 55),
      height: 55,
      child: new RaisedButton(
        color: Color(0xffFB5858),
        child: Text(
          "登录",
          style: Theme.of(context).primaryTextTheme.headline,
        ),
        // 设置按钮圆角
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(45.0)),
        onPressed: () async {
          //点击登录按钮，解除焦点，回收键盘
          _focusNodePassWord.unfocus();
          _focusNodeUserName.unfocus();

          if (_formKey.currentState.validate()) {
            print(_formKey.currentState.validate());
            //只有输入通过验证，才会执行这里
            _formKey.currentState.save();
            //todo 登录操作
            FormData formData = FormData.fromMap({
              "username": _userName,
              "password": _password,
            });
            var api = '${Config.loginUrl}';
            var response = await Dio().post(api, data: formData);
            // print(response);
            if (response.data["code"] == 0) {
              // Storage.setString('appKey', json.encode(response.data["data"]));
              Fluttertoast.showToast(
                msg: '${response.data["msg"]}',
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
              );
              print(json.encode(response.data["data"]));
              Navigator.pushNamed(context,
                  '/Home'); //使用的是“命名导航路由”，具体去哪个界面，看main.dart 对应routeName（'/Home'）的界面;
            } else {
              Fluttertoast.showToast(
                msg: '${response.data["msg"]}',
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
              );
            }
          }
        },
      ),
    );

    //忘记密码
    Widget bottomArea = new Container(
      margin: EdgeInsets.only(right: 55, left: 55),
      child: new Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          FlatButton(
            child: Text(
              "忘记密码?",
              style: TextStyle(
                color: Colors.white,
                fontSize: ScreenUtil().setSp(28),
              ),
            ),
            //忘记密码按钮，点击执行事件
            onPressed: () {
              Navigator.pushNamed(context, '/ForgetPassword');
            },
          )
        ],
      ),
    );

    return Scaffold(
      // 外层添加一个手势，用于点击空白部分，回收键盘
      body: new GestureDetector(
          onTap: () {
            // 点击空白区域，回收键盘
            _focusNodePassWord.unfocus();
            _focusNodeUserName.unfocus();
          },
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: NetworkImage(
                      "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1593176274503&di=9003ad102c989708e09a61f62f6c2dfc&imgtype=0&src=http%3A%2F%2Ft9.baidu.com%2Fit%2Fu%3D2313840380%2C776106152%26fm%3D193"),
                  fit: BoxFit.cover

                  ///AssetImage('images/driverBg.png'),
                  ),
            ),
            child: new ListView(
              children: <Widget>[
                new SizedBox(
                  height: ScreenUtil().setHeight(150),
                ),
                logoImageArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(70),
                ),
                inputTextArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(80),
                ),
                loginButtonArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(60),
                ),
                bottomArea,
              ],
            ),
          )),
    );
  }
}
